package com.chatgpt.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chatgpt.api.service.UserService;
import com.chatgpt.api.service.entity.User;
import com.chatgpt.api.vo.UserProfileVo;
import com.chatgpt.base.utils.StringUtil;
import com.chatgpt.base.vo.BizVo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author yangjian
 */
@RestController
@Slf4j
@RequestMapping("/api/user")
public class UserController extends BaseController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/list")
    public BizVo list() {
        List<User> users = userService.list();
        return BizVo.success().setData(users);
    }

    @Data
    @NoArgsConstructor
    protected static final class LoginParams {
        private String username;
        private String password;
    }

    @PostMapping("/login")
    public BizVo login(@RequestBody LoginParams param) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", param.getUsername());
        User user = userService.getOne(wrapper);
        if (user == null) {
            return BizVo.fail().setMessage("用户名不存在!");
        }

        String password = StringUtil.genPassword(param.getPassword(), user.getSalt());
        if (!StringUtils.equals(password, user.getPassword())) {
            return BizVo.fail().setMessage("密码错误！");
        }

        String token = userService.genToken(user.getId());
        return BizVo.success(token);
    }

    @GetMapping("/profile")
    public BizVo profile(HttpServletRequest request) {
        Integer userId = getLoginUserId(request);
        User user = userService.getById(userId);
        UserProfileVo profile = new UserProfileVo();
        BeanUtils.copyProperties(user, profile);
        return BizVo.success(profile);
    }

    @GetMapping("/session")
    public BizVo session(HttpServletRequest request) {
        User user = getLoginUser(request);
        return BizVo.success(user);
    }
}

